package mango.service.db.task;

import mango.Mango;


public class DBTask implements DBTaskProcessable {

    public static final int DB_EVENT_EXECUTE = 1;
    public static final int DB_EVENT_UPDATE = 2;
    public static final int DB_EVENT_SELECT_LIST_ENTITY = 3;
    public static final int DB_EVENT_SELECT_LIST_STRING = 4;
    public static final int DB_EVENT_SELECT_UNIQUE_STRING = 5;
    public static final int DB_EVENT_SELECT_UNIQUE_ENTITY = 6;

    private int eventId;
    private int subEventId;
    private DataHandler handler;
    private DataStruct dataStruct;
    private Object result;

    public DBTask(int eventId, int subEventId, DataHandler handler, DataStruct dataStruct) {
        this.eventId = eventId;
        this.subEventId = subEventId;
        this.handler = handler;
        this.dataStruct = dataStruct;
    }

    public boolean process() {
        try {
            switch (eventId) {
            case DB_EVENT_EXECUTE:
                result = this.dataStruct.getDao(eventId, subEventId).execute();
                break;
            case DB_EVENT_UPDATE:
                result = this.dataStruct.getDao(eventId, subEventId).executeUpdate();
                break;
            case DB_EVENT_SELECT_LIST_ENTITY:
                result = this.dataStruct.getDao(eventId, subEventId).listQuery();
                break;
            case DB_EVENT_SELECT_LIST_STRING:
                result = this.dataStruct.getDao(eventId, subEventId).listQueryString();
                break;
            case DB_EVENT_SELECT_UNIQUE_STRING:
                result = this.dataStruct.getDao(eventId, subEventId).getStringValue();
                break;
            case DB_EVENT_SELECT_UNIQUE_ENTITY:
                result = this.dataStruct.getDao(eventId, subEventId).uniqueResult();
                break;
            default:
                break;
            }
            return true;
        }
        catch(Exception e) {
            Mango.getLog().error("DBTask Process Error", e);
        }
        return false;
    }

    public void onBack() {
        if(this.handler != null) {
            this.handler.handleDB(eventId, subEventId, result);
        }
    }

}
